var invDetail_tabview = null;
var sel_inv_obj = null;

function open_sel_inv(invoiceNum){
	open_invoice_detail(invoiceNum);
}

function open_invoice_detail(invoiceNum){
	from_search = false;
	u_hideAllSections();
	u_safeShowElement('invdetails_div');
	if(invDetail_tabview == null){
		invDetail_tabview = new YAHOO.widget.TabView("invdetails_div_inner");
	}
	sel_inv_obj = null;
	
	if(search_found_cache && search_found_cache != null && search_found_cache.documentType == "INV"){
		for(var i=0;i<search_found_cache.length;i++){
			if(search_found_cache[i].invoiceNumber == invoiceNum){
				sel_inv_obj = search_found_cache[i];
				from_search = true;
				break;
			}
		}
	}
	
	try{
		if(sel_inv_obj == null){
			if(invsent_cache && invsent_cache != null && invsent_cache.length > 0){
				for(var i=0;i<invsent_cache.length;i++){
					if(invoiceNum == invsent_cache[i].invoiceNumber){
						 sel_inv_obj = invsent_cache[i];
	 					 assignAttachmentComponent("attachmentComponetPlaceHolder6");
						 assignCommentsComponent("commentComponetPlaceHolder6");
						 break;
					}
					
				}
			}
		}
	}catch(ex){}
	
	try{
		if(sel_inv_obj == null){
			if(inv_recdcache && inv_recdcache != null && inv_recdcache.length > 0){
				for(var i=0;i<inv_recdcache.length;i++){
					if(invoiceNum == inv_recdcache[i].invoiceNumber){
						 sel_inv_obj = inv_recdcache[i];
						 break;
					}
				}
			}
		}
	}catch(ex){}
	
	if(invsent_cache && invsent_cache != null){
		for(var i=0;i<invsent_cache.length;i++){
			if(sel_inv_obj.invoiceNumber == invsent_cache[i].invoiceNumber){
				$("inv_updateAction").style.display = "block";
				assignAttachmentComponent("attachmentComponetPlaceHolder6");
				assignCommentsComponent("commentComponetPlaceHolder6");
				dwr.util.setValue('target_comp_comment',"UPDATE_INV");
				dwr.util.setValue('target_comp_attachment',"UPDATE_INV");
				$("attph3_hdr").style.display = "block";
				$("attcm3_hdr").style.display = "block";
				break;
			} else{
				$('attachmentComponent').style.display='none';
				$('commentsComponent').style.display='none';
				$("inv_updateAction").style.display = "none";
				$("attph3_hdr").style.display = "none";
				$("attcm3_hdr").style.display = "none";
			}
		}
	}else{
		$('attachmentComponent').style.display='none';
		$('commentsComponent').style.display='none';
		$("inv_updateAction").style.display = "none";
		$("attph3_hdr").style.display = "none";
		$("attcm3_hdr").style.display = "none";
	}
	
	populate_invoice_details(sel_inv_obj);
	
	if(!isNavigationFromBackButton){
		var functionPointerObj = new Object();
		functionPointerObj.functionName = "open_invoice_detail("+"'"+invoiceNum+"'"+")";
		navigationStateArray.push(functionPointerObj);
	}
	
}

function populate_invoice_details(sel_inv_obj){
	dwr.util.setValue('invdetails_ponum',"");
	dwr.util.setValue('invdetails_version',"");
	dwr.util.setValue('invdetails_amt',"");
	dwr.util.setValue('inv_buyer_name',"");
	dwr.util.setValue('inv_supp_name',"");
	
	if(sel_inv_obj && sel_inv_obj != null){
		dwr.util.setValue('invdetails_ponum',sel_inv_obj.invoiceNumber);
		dwr.util.setValue('invdetails_version',sel_inv_obj.invoiceVersion);
		dwr.util.setValue('invdetails_amt',sel_inv_obj.totalInvoiceAmount);
		dwr.util.setValue('inv_buyer_name',sel_inv_obj.clientNameText);
		dwr.util.setValue('inv_supp_name',sel_inv_obj.supplierNameText);
		dwr.util.setValue('invdetails_relPO',sel_inv_obj.purchaseOrderNumber);
		
		if(sel_inv_obj.invoiceDate != null){
			dwr.util.setValue('invdetails_subdate',format_date(sel_inv_obj.invoiceDate));
			dwr.util.setValue('invdetails_recddate',format_date(sel_inv_obj.invoiceDate));
		}
		populate_attachmentForSelectedINV(sel_inv_obj);
		populate_commentsForSelectedINV(sel_inv_obj);
		inv_render_lineitems(sel_inv_obj);
		//Get history of the invoice
		populate_invh_table(sel_inv_obj.invoiceHistory);
		
		try{
			var paymentTermObj = getPaymentTerm(sel_inv_obj.orderPaymentTermId);
			$("inv_display_paymentTerm").innerHTML = paymentTermObj.desc;
			}catch(ex){
				$("inv_display_paymentTerm").innerHTML = "No Payment Term";
			}
			
			
	}
}

function populate_attachmentForSelectedINV(inv){
	try{
	dwr.util.removeAllRows("invDisplayattachments_tbody", {
		filter : function(tr) {
			return (tr.id != "invDisplayattachments_pattern");
		}
	});	
	if(inv.invoiceAttachmentsId != null){
	
		for(var i=0;i<inv.invoiceAttachmentsId.length;i++){
			var responseText = inv.invoiceAttachmentsId[i];
			var ids = i + ""
			dwr.util.cloneNode('invDisplayattachments_pattern', {idSuffix : ids});
			//dwr.util.setValue('poaattach_id'+i,o.responseText); //hidden field
			$("invDispalyattachments_link"+ids).setAttribute("href",'javascript:openAttachmentPanel("http://www.atsocii.com'+responseText.split(":")[1]+'");');
			$("invDispalyattachments_link"+ids).innerHTML = responseText.split(":")[3];
			$("invDisplayattachments_pattern"+ids).style.display = '';
		}
	}
	}catch(ex){}
}

function populate_commentsForSelectedINV(inv){
	
	try{
		dwr.util.removeAllRows("invDisplaycomments_tbody", {
			filter : function(tr) {
				return (tr.id != "invDisplaycomments_pattern");
			}
		});
		
		if(inv.invoiceComments != null){
		
			for(var i=0;i<inv.invoiceComments.length;i++){
				var responseText = inv.invoiceComments[i];
				var ids = i + ""
				dwr.util.cloneNode('invDisplaycomments_pattern', {idSuffix : ids});
				$("invDisplaycomment_text"+ids).innerHTML = responseText;
				$("invDisplaycomments_pattern"+ids).style.display = '';
			}
		}
		}catch(ex){}
}

function open_po_from_selected_inv(){
	open_sel_po(sel_inv_obj.purchaseOrderNumber);
}

var invlineItemReadOnlycolumnDefs = [ {
	key : "invoiceLineNumber",
	label : "Line",
	width : "50px"
	
}, {
	key : "partNumber",
	label : "Part Number",
	width : "50px"
	
},{
	key : "invoiceLineDescription",
	label : "Description",
	width : "50px"
}, {
	key : "quantity",
	label : "Quantity",
	width : "50px"
	
} ,{
	key : "uomSymbol",
	label : "Unit Of Measure",
	width : "50px"
} ,{
	key : "unitPrice",
	label : "Unit Price",
	width : "50px"
}  ,{
	key : "lineAmount",
	label : "Line Total",
	width : "50px"
}  ];


var inv_litems_yui_instance = null;

function clearlineitemsInvTable(){
	if(inv_litems_yui_instance != null && inv_litems_yui_instance.getRecordSet() != null && inv_litems_yui_instance.getRecordSet().getLength() > 0){
		inv_litems_yui_instance.deleteRows(0,inv_litems_yui_instance.getRecordSet().getLength());
	}
}

function inv_render_lineitems(inv){
	if(inv_litems_yui_instance == null){
		var liDataSource = new YAHOO.util.DataSource();
		liDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		inv_litems_yui_instance = new YAHOO.widget.DataTable("invlidetails_yui_table",invlineItemReadOnlycolumnDefs,liDataSource,{});
		inv_litems_yui_instance.set("selectionMode", "single");
		inv_litems_yui_instance.subscribe("rowClickEvent",
				inv_litems_yui_instance.onEventSelectRow);
	}
	clearlineitemsInvTable();
	if(inv.invoiceLineItems && inv.invoiceLineItems != null && inv.invoiceLineItems.length > 0){
		inv_litems_yui_instance.addRows(inv.invoiceLineItems);
	}
}


function updateInvoice(){
	
	try{
		var poNewAtchArr = new Array();
		if(attachmentctr > 0){
			for(var ip=0;ip<attachmentctr;ip++){
				if($('poattachments_check'+ip+'').checked){
					poNewAtchArr.push(dwr.util.getValue('poaattach_id'+ip+''));
				}
			}
		}
		
		
		
		
		var poNewCmtarr = new Array();
		if(pocomments_ctr > 0){
			for(var iq=0;iq<pocomments_ctr;iq++){
				if($('pocomment_check'+iq+'').checked){
					poNewCmtarr.push(dwr.util.getValue('pocomment_text'+iq+''));
				}
			}
		}
		
		
	}catch(ex){}
	
	var dwrCallMetaData = {
			callback : success_updateinv,
			exceptionHandler : exception_updateinv_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler
		};

	DWR_Invoice.updateInvoice(sel_inv_obj.invoiceNumber,poNewAtchArr,poNewCmtarr,loggedinuser,dwrCallMetaData);
	
}

function success_updateinv(dwrresp){
	if (dwrresp && dwrresp.respCode == 0) {
		if (dwrresp.objRespOrError != null
				&& !isEmptyString(dwrresp.objRespOrError)) {
			var invnum = dwrresp.objRespOrError.invoiceNumber;
			if(invsent_cache && invsent_cache != null){
				for(var i=0;i<invsent_cache.length;i++){
					if(invsent_cache[i].invoiceNumber == invnum){
						invsent_cache[i] = dwrresp.objRespOrError ;
						break;
					}
				}
			}		
			open_sel_inv(invnum);
			alert("Invoice Updated.");
		}
	} else{
		alert("Invoice could not be Updated. Please try again.");
	}
}

function exception_updateinv_handler(resp){
	//console.log(resp);
}

var invh_yui_table_instance = null;
var invhcolumnDefs = [ {
	key : "invoiceNumber",
	label : "Payment#"
}, {
	key : "invoiceVersion",
	label : "Invoice Version",
	formatter: "hlinkFormatter"	
},{
	key : "clientNameText",
	label : "Buyer",
	sortable : true
}, {
	key : "lastModifiedDate",
	label : "Last Modified Date",
	formatter: formatLastUpdateDate,
	sortable : true
}, {
	key : "lastModifiedBy",
	label : "Last Modified By",
	formatter: "date",
	sortable : true
} , {
	key : "totalInvoiceAmount",
	label : "Invoice Amount",
	formatter: "currency"
}];

function create_invh_results_table() {
	if(invh_yui_table_instance == null){
		var invsDataSource = new YAHOO.util.DataSource();
		invsDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		invh_yui_table_instance = new YAHOO.widget.DataTable("inv_history_yui_table",invhcolumnDefs,invsDataSource,{});
		invh_yui_table_instance.set("selectionMode", "single");
		invh_yui_table_instance.subscribe("rowClickEvent",invh_yui_table_instance.onEventSelectRow);
	}
}

function clear_invh_results_table() {
	if (invh_yui_table_instance != null) {
		var length = invh_yui_table_instance.getRecordSet().getLength();
		if (length > 0) {
			invh_yui_table_instance.deleteRows(0, length);
		}
	}
}

function populate_invh_table(history){
	create_invh_results_table();
	clear_invh_results_table();
	if(history != undefined && history != null && history.length > 0){
		/*for(var i=0;i<history.length;i++){
			history[i].clientNameText = sel_po_cache.clientNameText;
		}*/
		invh_yui_table_instance.addRows(history);
	}
}

function getinvverfrom_cache(ver){
	var ret = null;
	if(sel_inv_obj.invoiceHistory && sel_inv_obj.invoiceHistory != null && sel_inv_obj.invoiceHistory.length > 0){
		for(var idx=0; idx<sel_inv_obj.invoiceHistory.length;idx++){
			if(sel_inv_obj.invoiceHistory[idx].invoiceVersion == ver){
				ret = sel_inv_obj.invoiceHistory[idx];
				ret.invoiceHistory = sel_inv_obj.invoiceHistory;
				break;
			}
		}
	}
	
	return ret;
}

function open_sel_inv_ver(ver){
	u_hideAllSections();
	u_safeShowElement('invdetails_div');
	if(invDetail_tabview == null){
		invDetail_tabview = new YAHOO.widget.TabView("invdetails_div_inner");
	}
	invDetail_tabview.set('activeIndex',0);
	
	sel_inv_obj = getinvverfrom_cache(ver);
	
	populate_invoice_details(sel_inv_obj);
	
	if(invsent_cache && invsent_cache != null){
		for(var i=0;i<invsent_cache.length;i++){
			if(sel_inv_obj.invoiceNumber == invsent_cache[i].invoiceNumber
					&& sel_inv_obj.invoiceVersion == invsent_cache[i].invoiceVersion){
				$("inv_updateAction").style.display = "block";
				assignAttachmentComponent("attachmentComponetPlaceHolder6");
				assignCommentsComponent("commentComponetPlaceHolder6");
				dwr.util.setValue('target_comp_comment',"UPDATE_INV");
				dwr.util.setValue('target_comp_attachment',"UPDATE_INV");
				$("attph3_hdr").style.display = "block";
				$("attcm3_hdr").style.display = "block";
				break;
			} else{
				$('attachmentComponent').style.display='none';
				$('commentsComponent').style.display='none';
				$("inv_updateAction").style.display = "none";
				$("attph3_hdr").style.display = "none";
				$("attcm3_hdr").style.display = "none";
			}
		}
	}else{
		$('attachmentComponent').style.display='none';
		$('commentsComponent').style.display='none';
		$("inv_updateAction").style.display = "none";
		$("attph3_hdr").style.display = "none";
		$("attcm3_hdr").style.display = "none";
	}
}

function showasxml_inv(){
	var data = "";
	if(sel_inv_obj && sel_inv_obj != null){
		data = sel_inv_obj.invoiceXml;
	}
	showxmldata(data);
}

function showPO_inv(){
	var ponum = $("invdetails_relPO").innerHTML; 
	if(!isEmptyString(ponum)){
		open_sel_po(ponum);
	} else{
		alert("Please open PO from dashboard");
	}
			
}